#!/usr/local/bin/python
# -*- coding: utf-8 -*-

import datetime
from flask import Flask, url_for, request, session, render_template, redirect
from json import dumps

from bompy import app
from utils import q, table, login_required, get2parameters, formtable, textinput, unitoptions, designoptions, typeoptions
from model import Design, BOM


@app.route('/plode')
@login_required
@get2parameters
def plode(ID, ex=False):
    d = Design.getCurrent(ID).Description_Std
    t=table(["Parent ID","Description","Type","Child ID","Description","Type","Quantity","Unit","Created","By user","Updated","By user","","","",""])
    return render_template("plode.html", ID=ID, ex=ex, t=t)

    
@app.route('/_explode')
@get2parameters
def explode(ID, _=""):
    def exploderec(parent):
        for i in BOM.query.filter_by(ID_Parent=parent):
            if i.isMain():
                d["aaData"].append(i.table())
                exploderec(i.ID_Child)
    d={}
    d["aaData"]=[]
    exploderec(ID)
    
    return dumps(d)


@app.route('/_implode')
@get2parameters
def implode(ID, _=""):

    def imploderec(child):
        for i in BOM.query.filter_by(ID_Child=child):
            if i.isMain():
                d["aaData"].append(i.table())
                imploderec(i.ID_Parent)

    d={}
    d["aaData"]=[]
    imploderec(ID)
    
    return dumps(d)
